package com.zyf.chapter01.practice.v3;

import com.zyf.chapter01.practice.v2.Aggregator;
import com.zyf.chapter01.practice.v2.ConsoleViewer;
import com.zyf.chapter01.practice.v2.StatViewer;
import com.zyf.chapter01.principle.practice.MetricsStorage;
import com.zyf.chapter01.principle.practice.RedisMetricsStorage;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 将组装类中重复逻辑进行封装，使用父类将重复代码提取
 * 新增易用性 封装默认依赖
 * @since v3
 * @author yifeng
 */
public class ConsoleReporter extends ScheduledReqorter{
    private MetricsStorage metricsStorage;
    private Aggregator aggregator;
    private StatViewer viewer;
    private ScheduledExecutorService executor;

    // 兼顾代码的易用性，新增了一个封装默认依赖的构造函数
    public ConsoleReporter() {
        this(new RedisMetricsStorage(), new Aggregator(), new ConsoleViewer());
    }

    public ConsoleReporter(MetricsStorage metricsStorage, Aggregator aggregator,
                           StatViewer viewer) {
        super(metricsStorage, aggregator, viewer);
        this.executor = Executors.newSingleThreadScheduledExecutor();
    }


    public void startRepeatedReport(long periodInSeconds, long durationInSeconds) {
        executor.scheduleAtFixedRate((Runnable) () -> {
            // 第一个代码逻辑：根据给定的时间区间，从数据库中拉取数据;
            // 该代码逻辑不需要重构
            long durationInMillis = durationInSeconds * 1000;
            long endTimeInMillis = System.currentTimeMillis();
            long startTimeInMillis = endTimeInMillis - durationInMillis;
            doStartAndReport(startTimeInMillis, endTimeInMillis);
        }, 0, periodInSeconds, TimeUnit.SECONDS);
    }
}
